package day8;

import java.io.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;
import org.junit.Test;

public class FileDemo8 {

    HashMap<String, Integer> map = new HashMap<String, Integer>();
    @Test
    public void test() {
        Properties p = new Properties();

        //  /test.properties eclipse下的src下的文件  idea： 建议在工程创建一个文件夹，后面给文件夹标志为resource，灰黄色
        // idea:test.properties直接放文件夹里面  读取文件时不要加斜杠
        try(InputStream is = FileDemo8.class.getClassLoader().getResourceAsStream("score.txt")){

            //调用load
            p.load(is);

            //获取属性集
            Set<String> propertyNames = p.stringPropertyNames();
            for (String name : propertyNames) {
                if (!map.containsKey(name)) map.put(name, Integer.valueOf(p.getProperty(name)));
                if (name.equals("lisi")) map.put(name, 100);
            }
            Set sekpt = map.keySet();
            for (Object key : sekpt) {
                String o = (String) key;
                System.out.println("key为:" + o + "的values是:" + map.get(o));
                p.setProperty(o, String.valueOf(map.get(o)));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test2() throws IOException {
        Properties p = new Properties();
        File file = new File("");

        try(Reader r = new FileReader(file);
            BufferedReader br = new BufferedReader(r);

            Writer w = new FileWriter(file);){

            p.load(br);

            Set<String> names = p.stringPropertyNames();
            for (String name : names) {
                if (name.equals("lisi")) {
                    p.setProperty(name, 100 + "");
                    System.out.println("修改好了");

                    w.write(name + "=" + p.getProperty(name));
                    w.flush();
                }
                w.write(name + "=" + p.getProperty(name));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
